package com.elangzhi.ssm.modules.collection.app;

import com.elangzhi.ssm.controller.json.Tip;
import com.elangzhi.ssm.model.Collection;
import com.elangzhi.ssm.model.Goods;
import com.elangzhi.ssm.modules.collection.services.CollectionService;
import com.elangzhi.ssm.modules.goods.services.GoodsService;
import com.elangzhi.ssm.modules.image.services.ImageService;
import com.elangzhi.ssm.tools.UUIDFactory;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
* 用户商品收藏 客户端 Controller
* @author GaoXiang
* @version 1.0
*/
@Controller
@RequestMapping("/app/collection")
public class AppCollectionController {

    /**
     * 删除收藏
     * @param collection id
     * @return 成功状态
     */
    @RequestMapping("delete")
    @ResponseBody
    public Tip delete(Collection collection){
        try {
            collectionService.deleteById(collection.getId());
            return new Tip(collection);
        } catch (Exception e) {
            e.printStackTrace();
            return new Tip(1);
        }
    }

    /**
     * 添加收藏
     * @param collection 收藏参数（userId，goodsId）
     * @return 成功状态
     */
    @RequestMapping("save")
    @ResponseBody
    public Tip save(Collection collection){
        if(collectionService.isRepeat(collection)){
            return new Tip(2);
        }
        collection.setId(UUIDFactory.getLongId());
        collection.setSetTime(new Date());
        try {
            collectionService.insert(collection);
            return new Tip(collection);
        } catch (Exception e) {
            e.printStackTrace();
            return new Tip(1);
        }
    }

    /**
     * 根据用户id获取商品列表
     * @param userId 用户id
     * @param page 当前页数
     * @param size 每页大小
     * @return 收藏列表
     */
    @RequestMapping("listByUserId")
    @ResponseBody
    public PageInfo<Collection> listByUserId(
                  @RequestParam Long userId,
                  @RequestParam Integer page,
                  @RequestParam Integer size){
        PageInfo<Collection> collections = collectionService.listByUserId(userId,page,size);
        for(Collection collection : collections.getList()){
            Goods goods = goodsService.selectById(collection.getGoodsId());
            goods.setBannerList(imageService.listByTypeInfo(2,collection.getGoodsId()));
            collection.setGoods(goods);
        }
        return collections;
    }



    //---------------------------- property -------------------------------

    @Resource
    private CollectionService collectionService;

    @Resource
    private GoodsService goodsService;

    @Resource
    private ImageService imageService;

}
